# 使用提醒:
# 1. xbot包提供软件自动化、数据表格、Excel、日志、AI等功能
# 2. package包提供访问当前应用数据的功能，如获取元素、访问全局变量、获取资源文件等功能
# 3. 当此模块作为流程独立运行时执行main函数
# 4. 可视化流程中可以通过"调用模块"的指令使用此模块

# import xbot
# from xbot import print, sleep
# from . import package


def main(args):
    # r = error_log(alias="测试",type="3", pic_url="",pic_msg="",error_api="",other="测试")
    # print(r)
    pass


# -*- coding: utf-8 -*-
from .response_class import RequestsEdit
import json
from qiniu import Auth, put_file, etag
import qiniu.config
import requests
import os, re


def upload_img(img_name, img_path, alias, type) -> str:
    '''
    img_name: 图片名
    img_path: 图片本地地址
    alias:    商品id
    type:     平台标识
    '''
    # 获取token
    token = get_token()
    # 上传后保存的文件名
    key = img_name + ".png"
    # 本地文件地址
    localfile = img_path
    # 执行上传
    try:
        ret = put_file(token, key, localfile, version='v2')
        if ret[0]:
            # 解析返回地址
            img_path = ret[0].get("data", {}).get("attachmentPath", "")
            return img_path
        else:
            return None
    except:
        error_log(alias, type, img_path, str(ret[1]), "", "")


def get_token():
    """获取七牛token"""
    token_url = "http://gw.guang.com/v4/guangApp/upload/qiniu/api/getAutomatorUploadToken?channel=igclient_public"
    text_token = RequestsEdit.get(token_url)
    token = json.loads(text_token).get("data", {}).get("token", "")
    return token


def get_search_data(type):
    """获取任务"""
    url = "http://gw.guang.com/v4/guangApp/automator/api/getTask?type=%s" % type  # 平台类型,1:淘宝，2:拼多多，3:抖音
    text_task = RequestsEdit.get(url)
    task_data = json.loads(text_task).get("data", {})
    return task_data


def upload_data(goods_data):
    """回传抓取到的数据"""

    upload_url = "https://h5.guang.com/live/rpa/live/data.json"
    # data = json.dumps(goods_data)
    res = RequestsEdit.post(post_data=goods_data, url=upload_url)
    print(res)

def upload_data_notify(goods_data):
    """回传抓取到的数据"""

    upload_url = "http://gw.guang.com/guang-app-util/api/automator/returnClaimVideoLivingStatus"
    # data = json.dumps(goods_data)
    res = requests.get( url=upload_url, params=goods_data)
    print(res)


def get_devices():
    '''获取已经链接的手机id'''
    # devices_info = os.popen("C:\\Users\\有赞\\Desktop\\platform-tools\\adb.exe devices -l").read()
    devices_info = os.popen('''C:\\Users\\Admin\\Desktop\\platform-tools\\adb.exe devices -l''').read()
    splited_devices = devices_info.split('\n')[1:]

    result_list = []
    for device in splited_devices:
        if device:
            id = re.findall("(\w+) +device product", device)[0]
            result_list.append(id)

    print(result_list)
    return result_list


def pdd_login_error_msg(msg):
    '''拼多多登录异常回调接口'''
    url = "http://gw.guang.com/guang-app-util/api/feishu/defaultSend"
    res = RequestsEdit.post(post_data=msg, url=url)
    # print(res)


def error_log(alias, type, pic_url, pic_msg, error_api, other):
    '''异常返回接口'''

    error_log = {"alias": alias,
                 "shop": '',
                 "type": type,
                 "pic": {
                     "url": pic_url,
                     "msg": pic_msg,
                 },
                 "api": error_api,
                 "other": other,
                 }
    url = "http://gw.guang.com/guang-app-util/api/skylog/automatorLog"
    res = RequestsEdit.post(post_data=error_log, url=url)
    return res

def notice(name,startTime):
    content = "【主播名称：%s】；开始时间：【%s】"%(name,startTime)
    print(content)
    url = "http://gw.guang.com/guang-app-util/api/feishu/notifyToGroup"
    postParam ={
        "botkey": "f647f95b-50c3-4655-ab09-d16ec61f53aa",
        "card":{
            "config": {
                "wide_screen_mode": True,
                "enable_forward": True
            },
            "header": {
                "title": {
                    "content": "【%s】开播通知"%name,
                    "tag": "plain_text"
                 },
                "template": "blue"
            },
            "elements": [
                {
                    "tag": "markdown",
                    "content": "%s"%content
                }
            ]
        }
    }
    res = RequestsEdit.postWithoutProxy(post_data = postParam, url = url)
    print(res)
    return res